package com.wolf.etl.core.handler;

import com.alibaba.fastjson.JSONObject;
import com.wolf.etl.model.EtlApiModel;
import com.wolf.exception.ETL_ERROR_MSG;
import com.wolf.exception.WolfException;
import com.wolf.util.JsonUtil;
import com.wolf.util.http.HttpClientUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Objects;

/**
 * open api
 * 配置api 信息
 *
 * @author sdyang
 * @date 2019/11/23 11:26
 **/
public class ApiHandler extends AbstractHandler {

    private static Logger logger = LoggerFactory.getLogger(ApiHandler.class);

    @Override
    public JSONObject done(JSONObject data) {
        logger.info("api handler");

        if (handler_id == null) {
            WolfException.report(ETL_ERROR_MSG.ERROR_TRANSFORM_RULE_007, "api id is null");
        }

        EtlApiModel etlApi = manager.findApiById(handler_id);

        if (etlApi == null) {
            WolfException.report(ETL_ERROR_MSG.ERROR_TRANSFORM_RULE_007, String.format("找不到api id=%s", handler_id));
        }

        String url = etlApi.getUrl();
        JSONObject response = HttpClientUtil.post(url, JsonUtil.toJSONString(data), JSONObject.class);

        if (response == null) {
            WolfException.report(ETL_ERROR_MSG.ERROR_ELEMENT_003, "api调用结果为null");
        }

        if (Objects.isNull(handler)) {
            return response;
        }

        return this.handler.done(response);
    }

}
